package algo;

import java.util.ArrayList;
import java.util.HashMap;

import divTools.Converter;

import objects.Measurement;
import objects.ReferencePoint;

public class MapManager {
	
	/**
	 * Get the nearest reference point from the client
	 * @param referencePoints
	 * @param measurements
	 * @return
	 */
	public static ReferencePoint getReferencePoint(ArrayList<ReferencePoint> referencePoints, HashMap<String, Measurement> measurements) {
		
		int idxNearestRefPt = 0;
		float smallestDistance = Float.MAX_VALUE;
		
		for (int i = 0 ; i < referencePoints.size() ; i++) {
			float distance = computeDistance(measurements, referencePoints.get(i));
			if (distance < smallestDistance) {
				smallestDistance = distance;
				idxNearestRefPt = i;
			}
		}
		
		return referencePoints.get(idxNearestRefPt);
	}
	
	/**
	 * Computes the "distance" between a list of measurements and a reference point
	 * @param measurements
	 * @param refPoint
	 * @return
	 */
	public static float computeDistance(HashMap<String, Measurement> measurements, ReferencePoint refPoint) {
		
		float temp = 0;
		
		for (Measurement m1 : measurements.values()) {
			
			Measurement m2 = refPoint.getMeasurements().get(m1.getMacAdress());
			if (m2 != null) {
				temp += Math.pow(Converter.dBmToMw(m1.getPowerValue()) - Converter.dBmToMw(m2.getPowerValue()), 2);
			}				
		}
		
		return (float) Math.sqrt(temp);
	}
}